package com.crm.miaohe.controller.order;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.crm.miaohe.controller.PageResponse;
import com.crm.miaohe.controller.order.request.OrderAuthRequest;
import com.crm.miaohe.controller.order.request.OrderCustomRequest;
import com.crm.miaohe.controller.order.request.OrderDetailsModQtyRequest;
import com.crm.miaohe.controller.order.request.OrderExportRequest;
import com.crm.miaohe.controller.order.request.OrderFreightFeeRequest;
import com.crm.miaohe.controller.order.request.OrderPlanRequest;
import com.crm.miaohe.controller.order.request.OrderStatusRequest;
import com.crm.miaohe.entity.order.OrderEntity;
import com.crm.miaohe.entity.order.OrderFreightFeeEntity;
import com.crm.miaohe.kdcloud.api.Order;
import com.crm.miaohe.service.OrderService;
import com.crm.miaohe.service.OrderServiceImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import net.minidev.json.JSONObject;

@RestController
@RequestMapping("/api/erp/order")
public class OrderController {

    private final OrderServiceImpl orderServiceImpl;

    private final OrderService orderService;

    public OrderController(OrderService orderService, OrderServiceImpl orderServiceImpl) {
        this.orderService = orderService;
        this.orderServiceImpl = orderServiceImpl;
    }

    @PostMapping
    public ResponseEntity<Void> handlePostOrder(@RequestBody @Valid OrderPlanRequest request) throws ParseException {
        orderService.createOrder(request);
        return ResponseEntity.ok().build();
    }

    @GetMapping
    public ResponseEntity<List<Order>> queryOrders() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return ResponseEntity.ok(orderService.queryOrderDetail(username));
    }

    @PostMapping("/calcFreightFee")
    public ResponseEntity<OrderFreightFeeEntity> calcFreightFee(@RequestBody @Valid OrderFreightFeeRequest request) {
        return ResponseEntity.ok(orderService.calcFreightFee(request));
    }

    @GetMapping("/self")
    public ResponseEntity<PageResponse<OrderEntity>> queryCustomerOrders(@Valid OrderStatusRequest request) {
        return ResponseEntity.ok(orderService.getCustomerOrders(request));
    }

    @GetMapping("/checkCounts")
    public ResponseEntity<PageResponse<Integer>> checkTodayCounts(@Valid OrderPlanRequest request) {
        return ResponseEntity.ok(orderService.checkTodayOrders(request));
    }
    
    @GetMapping("/checkOrverDeposit")
    public ResponseEntity<PageResponse<JSONObject>> checkOrverDeposit(@Valid OrderPlanRequest request) {
        return ResponseEntity.ok(orderService.checkOverDeposit(request));
    }
    
    @PutMapping("/audit/{orderId}")
    public ResponseEntity<Void> auditOrder(@PathVariable Long orderId) {
        orderService.auditOrder(orderId);
        return ResponseEntity.ok().build();
    }
    @DeleteMapping("/{orderId}")
    public  ResponseEntity<Void> deleteOrder(@PathVariable Long orderId){
        orderService.deleteOrder(orderId);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/audit")
    public ResponseEntity<Void> auditOrders(@RequestBody OrderAuthRequest request) {

        // 放在要检测的代码段前，取开始前的时间戳
        //Long startTime = System.currentTimeMillis();

        orderService.auditOrders(Arrays.asList(request.getOrderIds()));

        // 放在要检测的代码段后，取结束后的时间戳
        //Long endTime = System.currentTimeMillis();

        // 计算并打印耗时
        /*Long tempTime = (endTime - startTime);
        System.out.println("订单接口保存花费时间："+
                (((tempTime/86400000)>0)?((tempTime/86400000)+"d"):"")+
                ((((tempTime/86400000)>0)||((tempTime%86400000/3600000)>0))?((tempTime%86400000/3600000)+"h"):(""))+
                ((((tempTime/3600000)>0)||((tempTime%3600000/60000)>0))?((tempTime%3600000/60000)+"m"):(""))+
                ((((tempTime/60000)>0)||((tempTime%60000/1000)>0))?((tempTime%60000/1000)+"s"):(""))+
                ((tempTime%1000)+"ms"));*/

        return ResponseEntity.ok().build();
    }

//    @GetMapping("/summary")

//    @GetMapping("/history")

    @GetMapping("/export")
    public ResponseEntity<Void>export(@Valid OrderExportRequest request, HttpServletResponse response){
        orderService.exportCustomerOrders(request,response);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/exportERP")
    public ResponseEntity<Void>advanceExport(@RequestParam("queryString") String queryString, HttpServletResponse response){
        String cond = URLDecoder.decode(queryString, StandardCharsets.UTF_8);
        Gson gson = new GsonBuilder().serializeNulls().create();
        OrderCustomRequest request =  gson.fromJson(cond,OrderCustomRequest.class);
        if(request!=null){
            orderService.exportERPOrders(request,response);
        }
        return ResponseEntity.ok().build();
    }

    @PostMapping("/addOutqty")
    public ResponseEntity<Void> addOutqty(@Valid @RequestBody String queryString, HttpServletResponse response){
        String cond = URLDecoder.decode(queryString, StandardCharsets.UTF_8);
        Gson gson = new GsonBuilder().serializeNulls().create();
        OrderDetailsModQtyRequest request =  gson.fromJson(cond,OrderDetailsModQtyRequest.class);
        if(request!=null){
            orderService.modOutQty(request,response,"add");
        }
        return ResponseEntity.ok().build();
    }
    @PostMapping("/subOutqty")
    public ResponseEntity<Void> subOutqty(@Valid @RequestBody String queryString, HttpServletResponse response){
        String cond = URLDecoder.decode(queryString, StandardCharsets.UTF_8);
        Gson gson = new GsonBuilder().serializeNulls().create();
        OrderDetailsModQtyRequest request =  gson.fromJson(cond,OrderDetailsModQtyRequest.class);
        if(request!=null){
            orderService.modOutQty(request,response,"sub");
        }
        return ResponseEntity.ok().build();
    }
    
    @PostMapping("/status/{orderNo}/{orderStatus}")
    public ResponseEntity<Void> updateStatus(@PathVariable String orderNo, @PathVariable String orderStatus) {
    	orderService.updateStatus(orderNo, orderStatus);
        return ResponseEntity.ok().build();
    }
}
